package gu.sql2java.manager;

import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.base.Preconditions.checkArgument;

import java.util.Map;

import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;

import gu.sql2java.Constant;
import gu.sql2java.manager.mysql.MysqlSqlFormatter;
import gu.sql2java.manager.phoenix.PhonenixSqlFormatter;

/**
 * @author guyadong
 * @since 3.14.0
 */
public class SqlFormatters implements Constant{
    private static Map<String, SqlFormatter> sqlFormatters = 
            ImmutableMap.of(
                    PRODUCT_NAME_PHOENIX,new PhonenixSqlFormatter(),
                    PRODUCT_NAME_MYSQL,new MysqlSqlFormatter());
    private static SqlFormatter DEFAULT_INSTANCE= new SqlFormatterAdapter();
    public static SqlFormatter formatterOf(String engine){
        return sqlFormatters.getOrDefault(engine, DEFAULT_INSTANCE);
    }
    
    public static class SqlFormatterAdapter implements SqlFormatter {

        @Override
        public String tablename(String tablename) {
            return tablename;
        }

        @Override
        public String columname(String columname) {
            return columname;
        }
        @Override
        public String alias(String alias) {
            return alias;
        }

    }
    public static class QuoteFormatter extends SqlFormatterAdapter{
        private final String quote;

        public QuoteFormatter(String quote) {
            super();
            checkArgument(!isNullOrEmpty(quote),"quote is null or empty");
            this.quote = quote;
        }

        /**
         * 如果输入字符串{@code input}以{@code quote}开头和结尾返回{@code true},否则返回{@code false}
         * @param input
         */
        protected boolean isQuoteWith(String input){
            if(null != input){
                return input.startsWith(quote) && input.endsWith(quote);
            }
            return false;
        }
        
        protected String quoteIf(String input, Predicate<String> and) {
            if(null != input && !isQuoteWith(input) && and.apply(input)){
                return quote + input + quote;
            }
            return input;
        }
        
        @Override
        public String alias(String alias) {
            return  columname(alias);
        }
    }
}
